using IRepository;
using IServices;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YL.Core.Entity;
using YL.Utils.Excel;
using YL.Utils.Extensions;
using YL.Utils.Json;
using YL.Utils.Pub;
using YL.Utils.Table;

namespace Services
{
    public class Wms_materialServices : BaseServices<Wms_material>, IWms_materialServices
    {
        private readonly IWms_materialRepository _repository;
        private readonly SqlSugarClient _client;

        public Wms_materialServices(SqlSugarClient client, IWms_materialRepository repository) : base(repository)
        {
            _client = client;
            _repository = repository;
        }

        public List<Wms_material> GetAllMaterials()
        {
            var mList = _client.Queryable<Wms_material>()
                 .Where(s => s.IsDel == 1)
                 .ToList();

            return mList;
        }

        public List<Wms_material> GetAllMaterialsBySource(int source)
        {
            var mList = new List<Wms_material>();

            if (source == 1)
            {
                mList = _client.Queryable<Wms_material>()
                     .Where(s => s.IsDel == 1 && (s.Source == 1 || s.Source == 0))
                     .OrderBy(s => s.InOrderNo)
                     .ToList();
            }
            else
            {
                mList = _client.Queryable<Wms_material>()
                    .Where(s => s.IsDel == 1 && (s.Source == 2 || s.Source == 0))
                    .OrderBy(s => s.OutOrderNo)
                    .ToList();
            }

            return mList;
        }

        public string GetAllMaterialIdJson()
        {
            var mList = _client.Queryable<Wms_material>()
                .Where(s => s.IsDel == 1)
                .ToList();

            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (var item in mList)
            {
                sb.Append(string.Format("'m_{0}':'',", item.MaterialId.ToString()));
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("}");

            string jsonStr = sb.ToString();
            return jsonStr;
        }

        public string PageList(Bootstrap.BootstrapParams bootstrap)
        {
            int totalNumber = 0;
            if (bootstrap.offset != 0)
            {
                bootstrap.offset = bootstrap.offset / bootstrap.limit + 1;
            }
            var query = _client.Queryable<Wms_material>()
                 .Where(s => s.IsDel == 1);

            if (!bootstrap.datemin.IsEmpty())
            {
                query.Where(s => s.CreateDate > bootstrap.datemin.ToDateTimeB());
            }
            if (!bootstrap.datemax.IsEmpty())
            {
                query.Where(s => s.CreateDate <= bootstrap.datemax.ToDateTimeE());
            }
            if (bootstrap.sort.IsEmpty())
            {
                bootstrap.sort = "CreateDate";
            }
            if (!bootstrap.search.IsEmpty())
            {
                query.Where(s => s.MaterialName.Contains(bootstrap.search));
            }
            if (bootstrap.order.Equals("desc", StringComparison.OrdinalIgnoreCase))
            {
                query.OrderBy($"{bootstrap.sort} desc");
            }
            else
            {
                query.OrderBy($"{bootstrap.sort} asc");
            }
            var list = query.Select(x => new
            {
                MaterialId = x.MaterialId.ToString(),
                MaterialName = x.MaterialName,
                CreateBy = x.CreateBy,
                Remark = x.Remark,
                CreateDate = x.CreateDate,
                Unit = x.Unit,
                Source = x.Source,
                InOrderNo=x.InOrderNo,
                OutOrderNo=x.OutOrderNo
            }).ToPageList(bootstrap.offset, bootstrap.limit, ref totalNumber);
            string jsonStr = Bootstrap.GridData(list, totalNumber).JilToJson();
            return jsonStr;
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="matIdList"></param>
        /// <returns></returns>
        public bool OrderMatList(List<long> matIdList, int source)
        {
            var allMatList = this._client.Queryable<Wms_material>().ToList();

            List<Wms_material> updateMatList = new List<Wms_material>();

            try
            {
                // source=1 表示入库  source=2 表示出库
                if (source == 1)
                {
                    for (int i = 0; i < matIdList.Count; i++)
                    {
                        var matId = matIdList[i];
                        var curMat=allMatList.Where(x => x.MaterialId == matId).First();
                        if (curMat.InOrderNo != i)
                        {
                            curMat.InOrderNo = i;
                            updateMatList.Add(curMat);   
                        }
                    }

                    if (updateMatList.Count > 0)
                    {
                        this._client.Updateable(updateMatList).UpdateColumns(x => new { x.InOrderNo }).ExecuteCommand();
                    }
                }
                else
                {
                    for (int i = 0; i < matIdList.Count; i++)
                    {
                        var matId = matIdList[i];
                        var curMat = allMatList.Where(x => x.MaterialId == matId).First();
                        if (curMat.OutOrderNo != i)
                        {
                            curMat.OutOrderNo = i;
                            updateMatList.Add(curMat);
                        }
                    }

                    if (updateMatList.Count > 0)
                    {
                        this._client.Updateable(updateMatList).UpdateColumns(x => new { x.OutOrderNo }).ExecuteCommand();
                    }
                }
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        public byte[] ExportList(Bootstrap.BootstrapParams bootstrap)
        {
            bootstrap.sort = "创建时间";
            bootstrap.order = "desc";
            var query = _client.Queryable<Wms_material>()
                 .Where(s => s.IsDel == 1)
                 .Select(s => new
                 {
                     物料名称 = s.MaterialName,
                     计量单位 = s.Unit,
                     备注 = s.Remark,
                     创建时间 = s.CreateDate
                 });
            if (!bootstrap.datemin.IsEmpty() && !bootstrap.datemax.IsEmpty())
            {
                query.Where(s => s.创建时间 > bootstrap.datemin.ToDateTimeB() && s.创建时间 <= bootstrap.datemax.ToDateTimeE());
            }

            if (bootstrap.order.Equals("desc", StringComparison.OrdinalIgnoreCase))
            {
                query.OrderBy($"{bootstrap.sort} desc");
            }
            else
            {
                query.OrderBy($"{bootstrap.sort} asc");
            }
            var list = query.ToList();
            var buffer = NpoiUtil.Export(list, ExcelVersion.V2007);
            return buffer;
        }
    }
}